<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>工时填报</span>
      </div>

      <el-form :model="headForm" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="编号" prop="no">
              <el-input
                v-model="headForm.no"
                placeholder="请输入编号"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input
                v-model="headForm.name"
                placeholder="请输入姓名"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门" prop="dept">
              <el-input
                v-model="headForm.dept"
                placeholder="请输入部门"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="填报日期" prop="date">
              <el-date-picker
                v-model="headForm.date"
                type="datetime"
                placeholder="请输入填报日期"
                style="width: 100%"
                disabled
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider style="margin: 12px 0" />

        <div style="padding: 0px 0px 15px">
          <span>今天已填报记录</span>
        </div>
        <el-row>
          <el-col :span="24">
            <el-table :data="initData" style="width: 100%">
              <el-table-column
                prop="number"
                label="序号"
                type="index"
                width="80"
                align="center"
              >
                <template slot-scope="scope">
                  <span>{{ (scope.row.number = scope.$index + 1) }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="projectCode"
                label="项目代码"
                width="120"
              />
              <el-table-column prop="stageName" label="开发阶段" width="120" />
              <el-table-column prop="officeName" label="事务种类" />
              <el-table-column
                label="申报日期"
                prop="workTime"
                align="center"
                width="180"
              >
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.workTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="workHour"
                label="工时(H)"
                align="center"
                width="80"
              />
              <el-table-column
                prop="workRemark"
                label="备注"
                show-overflow-tooltip
              />
            </el-table>
          </el-col>
        </el-row>
        <el-divider style="margin: 12px 0" />

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              >添加行</el-button
            >
          </el-col>

          <el-col :span="1.5" style="float: right">
            <el-button
              type="success"
              plain
              icon="el-icon-check"
              size="mini"
              @click="handleSave"
              >提交</el-button
            >
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-table :data="tableData" style="width: 100%">
              <el-table-column
                prop="number"
                label="序号"
                type="index"
                width="80"
                align="center"
              >
                <template slot-scope="scope">
                  <span>{{ (scope.row.number = scope.$index + 1) }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="projectCode"
                label="项目代码"
                width="120"
              />
              <el-table-column prop="stageName" label="开发阶段" width="120" />
              <el-table-column prop="officeName" label="事务种类" />
              <el-table-column
                label="申报日期"
                prop="workTime"
                align="center"
                width="180"
              >
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.workTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="workHour"
                label="工时(H)"
                align="center"
                width="80"
              />
              <el-table-column
                prop="workRemark"
                label="备注"
                show-overflow-tooltip
              />
              <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
                width="120"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                    >修改</el-button
                  >
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 新增、修改 弹框 -->
    <el-dialog
      title="工时填报"
      :visible.sync="open"
      v-if="open"
      width="500px"
      append-to-body
    >
      <el-form
        ref="detailForm"
        :model="detailForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="项目代码" prop="projectId">
          <el-select
            v-model="detailForm.projectId"
            placeholder="请输入项目代码"
            clearable
            filterable
            style="width: 100%"
            @change="changeProject"
          >
            <el-option
              v-for="item in projectOptions"
              :key="item.projectId"
              :label="item.projectCode"
              :value="item.projectId"
              :hidden="item.status == 1"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目开发阶段" prop="stageName">
          <el-input
            v-model="detailForm.stageName"
            placeholder="请输入当前项目开发阶段"
            disabled
          />
        </el-form-item>
        <el-form-item label="事务类型" prop="officeId">
          <el-select
            v-model="detailForm.officeId"
            placeholder="请输入事务类型"
            clearable
            filterable
            style="width: 100%"
            @change="changeOffice"
          >
            <el-option
              v-for="item in officeOptions"
              :key="item.officeId"
              :label="item.officeName"
              :value="item.officeId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申报日期" prop="workTime">
          <el-date-picker
            v-model="detailForm.workTime"
            type="datetime"
            placeholder="选择申报日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="工时(H)" prop="workHour">
          <el-input-number
            v-model="detailForm.workHour"
            controls-position="right"
            :min="0.5"
            :max="24"
            :step="0.5"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="workRemark">
          <el-input
            v-model="detailForm.workRemark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { init, fillSave } from '@/api/work/fill'
import { optionSelect as getOffices } from '@/api/work/office'
import { optionSelect as getProjects } from '@/api/work/project'

export default {
  name: 'Fill',
  data() {
    return {
      // 是否显示弹出层
      open: false,
      // 头表单
      headForm: {},
      // 初始化今天已填报数据
      initData: [],
      // 填报明细表单
      detailForm: {},
      // 表单校验
      rules: {
        projectId: [
          { required: true, message: '项目代码不能为空', trigger: 'change' }
        ],
        officeId: [
          { required: true, message: '事务种类不能为空', trigger: 'change' }
        ],
        workTime: [
          { required: true, message: '申报日期不能为空', trigger: 'blur' }
        ],
        workHour: [
          { required: true, message: '工时不能为空', trigger: 'blur' }
        ],
        workRemark: [
          { required: true, message: '备注不能为空', trigger: 'blur' }
        ]
      },
      // 表单数据
      tableData: [],
      // 项目选项
      projectOptions: [],
      // 所有事务类型选项
      allOfficeOptions: [],
      // 事务类型选项
      officeOptions: []
    }
  },
  created() {
    this.initFill()
  },
  methods: {
    /** 初始化填报表单 */
    initFill() {
      const info = this.$store.state.user.info
      this.headForm = {
        userId: info.userId,
        no: info.userName,
        name: info.nickName,
        dept: info.deptName,
        date: new Date()
      }
      // 初始化当天已填数据
      this.initNowDateTable()
    },
    /** 初始化当天已填数据 */
    initNowDateTable() {
      init().then((response) => {
        this.initData = response.data
      })
    },
    /** 重置填报表单 */
    resetDetailForm() {
      this.detailForm = {
        projectId: '',
        projectCode: '',
        stageId: '',
        stageName: '',
        officeId: '',
        officeName: '',
        workTime: new Date(),
        workHour: 0,
        workRemark: ''
      }
    },
    /** 添加行操作 */
    handleAdd() {
      this.resetDetailForm()
      this.getProjects()
      this.getOffices()
      this.open = true
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.resetDetailForm()
      let copy = Object.assign({}, row) //row是所编辑本行内数据对象
      this.detailForm = copy
      this.getProjects()
      this.getOffices()
      this.open = true
    },
    /** 删除行操作 */
    handleDelete(row) {
      this.tableData.splice(row.number - 1, 1)
    },
    /** 初始化项目下拉 */
    getProjects() {
      getProjects().then((response) => {
        this.projectOptions = response.data
      })
    },
    /** 初始化事务种类下拉 */
    getOffices() {
      getOffices().then((response) => {
        this.allOfficeOptions = response.data
      })
    },
    /** 选择项目，带出开发阶段 */
    changeProject(data) {
      let offices = this.allOfficeOptions
      if (data) {
        let option = this.projectOptions.find((i) => i.projectId == data)
        this.detailForm.projectCode = option.projectCode
        this.detailForm.stageId = option.stageId
        this.detailForm.stageName = option.stageName
        // Other阶段，不对应项目代码
        if (option.stageName === 'Other') {
          this.officeOptions = offices.filter((e) => e.officeId != 1)
        } else {
          // 其他开发阶段，对应项目代码
          this.officeOptions = offices.filter((e) => e.officeId === 1)
        }
      } else {
        this.detailForm.projectId = undefined
        this.detailForm.projectCode = undefined
        this.detailForm.stageId = undefined
        this.detailForm.stageName = undefined
        this.detailForm.officeId = undefined
        this.detailForm.officeName = undefined
        this.officeOptions = []
      }
    },
    /** 选择事务种类 */
    changeOffice(data) {
      if (data) {
        let option = this.officeOptions.find((i) => i.officeId == data)
        this.detailForm.officeId = option.officeId
        this.detailForm.officeName = option.officeName
      } else {
        this.detailForm.officeId = undefined
        this.detailForm.officeName = undefined
      }
    },
    /** 取消按钮 */
    cancel() {
      this.resetDetailForm()
      this.open = false
    },
    /** 验证 每天时间总和不超过24小时 */
    verifyTime(data) {
      let flag = false
      let sum = 0
      let arrquantitynew = this.tableData
        .filter(
          (i) =>
            i.number != data.number &&
            this.parseTime(i.workTime, '{y}-{m}-{d}') ==
              this.parseTime(data.workTime, '{y}-{m}-{d}')
        )
        .map((item) => {
          return item.workHour
        })
      if (arrquantitynew && arrquantitynew.length > 0) {
        sum = arrquantitynew.reduce((x, y) => x + y)
      }
      if (sum + data.workHour > 24) {
        flag = true
      }
      return flag
    },
    /** 验证 明细中开发日期字段不为空 */
    verify() {
      let flag = false
      let res = this.tableData.filter((i) => this.parseStrEmpty(i.workTime))
      if (res && res.length < this.tableData.length) {
        flag = true
      }
      return flag
    },
    /** 填报明细提交按钮 */
    submitForm() {
      this.$refs['detailForm'].validate((valid) => {
        if (valid) {
          const detailInfo = this.detailForm
          if (this.verifyTime(this.detailForm)) {
            /** 填报工时总和不能超过24小时 */
            this.$message.warning(
              '提示：日期 ' +
                this.parseTime(this.detailForm.workTime, '{y}-{m}-{d}') +
                ' 填报工时 总和 不能超过24小时'
            )
          } else {
            /** 保存 */
            if (detailInfo.number) {
              this.tableData = this.tableData.map((item) =>
                item.number === detailInfo.number ? detailInfo : item
              )
            } else {
              this.tableData.push(detailInfo)
            }
            this.tableData.sort((a, b) => {
              return a.workTime - b.workTime
            })
            this.open = false
          }
        }
      })
    },
    /** 填报完成 */
    handleSave() {
      if (this.tableData && this.tableData.length > 0) {
        /** 验证 */
        if (this.verify()) {
          this.$message.warning('提示：开发工作日期不能为空')
        } else {
          const saveFrom = {
            userId: this.headForm.userId,
            fillTime: this.headForm.date,
            fillStartTime: this.headForm.date,
            fillEndTime: new Date(),
            fillDetails: this.tableData
          }
          fillSave(saveFrom).then((response) => {
            this.$modal.msgSuccess(response.msg)
            this.tableData.splice(0, this.tableData.length)
            this.initFill()
          })
        }
      } else {
        this.$message.warning('提示：填报明细不能为空')
      }
    }
  }
}
</script>
